package com.example.shiroplusdemo.service;

import com.example.shiroplusdemo.entity.PermissionInit;
import com.example.shiroplusdemo.repository.PermissionInitRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-09
 **/
@Service
@Slf4j
public class ShiroService {

    @Autowired
    private ShiroFilterFactoryBean shiroFilterFactoryBean;

    @Autowired
    private PermissionInitRepository permissionInitRepository;

    /**
     * 初始化权限
     * @return
     */
    public Map<String,String> loadFilterChainDefinitions(){
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        //从数据库中获取初始化权限／add perms[权限添加]
        List<PermissionInit> permissionInitList = permissionInitRepository.findAll();
        for(PermissionInit permissionInit:permissionInitList){
            filterChainDefinitionMap.put(permissionInit.getUrl(),permissionInit.getPermissionInit());
        }
        return filterChainDefinitionMap;
    }

    /**
     * 重新加载权限
     */
    public void updatePermission(){
        synchronized (shiroFilterFactoryBean){
            AbstractShiroFilter shiroFilter = null;
            try{
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
            }catch(Exception e ){
                throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
            }

            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();

            //清空旧的权限控制
            manager.getFilterChains().clear();
            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitions());
            //重新构建生成manager中的
            Map<String,String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
            for(Map.Entry<String,String> entry: chains.entrySet()){
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ","");
                manager.createChain(url,chainDefinition);
            }

            log.info("权限更新成功");
        }
    }
}
